﻿using System.Collections;
using UnityEngine;
using UnityEngine.Events;

namespace Easy.Game2d
{
    public class BossItem : MonoBehaviour
    {
        #region data
        public float _bulletSpeed = 2;
        private float _hp = 150;
        private Transform _player;
        private UnityAction _unityAction;
        #endregion

        #region logic - Monster move
        public void StartCor(Transform player,float hp, UnityAction unityAction)
        {
            _hp = hp;
            _player = player;
            _unityAction = unityAction;
            StartCoroutine(WaitBossBullet());
        }
        private IEnumerator WaitBossBullet()
        {
            while (true)
            {
                CreateBullet();
                yield return new WaitForSeconds(1.5f);
            }
        }

 
        private void CreateBullet()
        {

            Vector3 playerPos = _player.position;

            // 子弹角度
            float fireAngle = Vector2.Angle(playerPos - this.transform.position, Vector2.up);
            if (playerPos.x > this.transform.position.x)
            {
                fireAngle = -fireAngle;
            }

            GameObject bullets = Resources.Load<GameObject>("Models/BulletsBoss");
            GameObject bullet = Instantiate(bullets, transform.position, Quaternion.identity) as GameObject;
            bullet.GetComponent<Rigidbody2D>().velocity = ((playerPos - transform.position).normalized * _bulletSpeed);
            bullet.transform.eulerAngles = new Vector3(0, 0, fireAngle);


        }
        #endregion

        #region trigger
        private void OnTriggerEnter2D(Collider2D collision)
        {
            if (collision.CompareTag("bullet"))
            {
                //_hp--;
               int damage= collision.GetComponent<BulletItem>().damage;
                _hp -= damage;
                Destroy(collision.gameObject);
                if (_hp <= 0)
                {
                    _unityAction?.Invoke();
                    StartCoroutine(WaitDes());
                }
            }
        }
        private IEnumerator WaitDes()
        {
            this.transform.localScale = new Vector3(0, 0, 0);
            yield return new WaitForSeconds(2);
            Destroy(this.gameObject);
        }
        #endregion
    }

}